//------------------------------------------------------------------------------
//  TestRenderApp.cpp
//  (C) 2010 xoyojank
//------------------------------------------------------------------------------
#include "StdAfx.h"
#include "TestRenderApp.h"
#include "Graphics/Nvx2MeshLoader.h"

using namespace Eddy;

//------------------------------------------------------------------------------
bool
TestRenderApp::Open()
{
	if (RenderApplication::Open())
	{
		// mesh
		this->mesh = new Mesh();
		this->mesh->SetName(L"mesh\\dice.nvx2");
		ResourceLoaderPtr loader = new Nvx2MeshLoader();
		this->mesh->SetLoader(loader);
		this->mesh->Load();
		this->mesh->ApplyPrimitiveGroup(0);

		// effect
		this->effect = EffectManager::Instance()->CreateEffect(
			L"shader\\lighting.vp.bin", L"shader\\lighting.fp.bin");
		this->worldViewMatrix = this->effect->GetVariable("mViewModel");
		this->projectMatrix = this->effect->GetVariable("mProject");
		const EffectVariablePtr& varLightDir = this->effect->GetVariable("vLightDir");
		varLightDir->SetVector(vector(0.5f, -1.0f, -0.5f));

		matrix44 project = matrix44::orthorh(2.0f, 3.0f, 1.0f, 100.0f);
		this->projectMatrix->SetMatrix(project);

		return true;
	}

	return false;
}

//------------------------------------------------------------------------------
void
TestRenderApp::Close()
{
	this->mesh = NULL;
	RenderApplication::Close();
}

//------------------------------------------------------------------------------
void
TestRenderApp::OnRenderFrame()
{

	this->renderDevice->Clear();

	this->renderDevice->BeginPass(this->effect);
	this->renderDevice->Draw();
	this->renderDevice->EndPass();

	this->renderDevice->Present();
}

//------------------------------------------------------------------------------
void
TestRenderApp::OnUpdateFrame()
{
	assert(this->worldViewMatrix.isvalid());
	assert(this->projectMatrix.isvalid());

	// transform matrix
	matrix44 transform = matrix44::rotationy((float)this->GetTime() * 0.0001f);
	transform.scale(vector(0.5f, 0.5f, 0.5f));
	transform.translate(vector(0.5f, 0.5f, 0.0f));

	matrix44 view = matrix44::lookatrh(point(0, 0, 1), point(), vector(0, 1, 0));

	transform = matrix44::multiply(transform, view);
	this->worldViewMatrix->SetMatrix(transform);
}